<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class Pay extends Command
{
    protected $result = [
        'msg' => '',
        'result' => false
    ];

    public function __construct()
    {
        parent::__construct();
        $this->BusinessModel = new \app\common\model\Business\Business();
        $this->RecordModel = new \app\common\model\Business\Record();
        $this->PayModel = new \app\common\model\Pay\Pay();
        $this->SubjectModel =  new \app\common\model\Subject\Subject();
        $this->ReceiveModel = new \app\common\model\Coupon\Receive();
        $this->OrderModel = new \app\common\model\Subject\Order();
        $this->CommissionModel = new \app\common\model\Business\Commission();
    }
    protected function configure()
    {
        $this->setName('pay')->setDescription('更新支付订单状态为【已支付】');
    }

    protected function execute(Input $input, Output $output)
    {
        $list = Db::name('pay')->where('status', '0')->select();

        if (!$list) {
            $output->info('目前暂无待支付的订单');
            return false;
        }

        // foreach ($list as $item)
        // {
        //     if ($item['name'] == "余额充值")
        //     {
        //         $sucess = $this->business($item['id']);
        //         $output->info($sucess['msg']);
        //     }
        //     else if ($item['name'] == '课程购买')
        //     {
        //         $success = $this->subject($item['id']);
        //         $output->info($success['msg']);
        //     }
        // }

        $ids = [];

        foreach ($list as $item) {

            $createtime = strtotime($item['createtime'])  + 60 * 3;

            if (time() > $createtime) {
                $ids[] = $item['id'];
            }
        }

        if ($ids) {
            $result = Db::name('pay')->where('id', 'IN', $ids)->update(['status' => '2']);

            if ($result === false) {
                return $output->error("执行数据库语句失败");
                exit;
            }
        }

        $output->info('执行完毕');
        return false;
    }

    // 用户充值
    public function business($ids = null)
    {
        //查询充值记录
        $row = $this->PayModel->find($ids);

        if (!$row) {
            $this->result['msg'] = '支付订单不存在';
            $this->result['result'] = false;
            return $this->result;
        }

        // 充值的金额
        $total = isset($row['total']) ? $row['total'] : 0;
        $total = floatval($total);

        // 第三方参数(可多参数)
        $third = isset($row['third']) ? $row['third'] : '';

        // json字符串转换数组
        $third = json_decode($third, true);

        // 从数组获取充值的用户id
        $busid = isset($third['busid']) ? $third['busid'] : 0;

        // 支付方式
        $type = isset($row['type']) ? $row['type'] : 'zfb';
        $payment = $type == "zfb" ? "支付宝" : "微信支付";

        //判断用户是否存在
        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->result['msg'] = '充值用户不存在';
            $this->result['result'] = false;
            return $this->result;
        }

        //判断充值金额
        if ($total <= 0) {
            $this->result['msg'] = '充值金额不能为0';
            $this->result['result'] = false;
            return $this->result;
        }

        // 开启事务
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();
        $this->PayModel->startTrans();

        // 余额 + 充值的金额
        $money = bcadd($business['money'], $total, 2);

        $BusinessData = [
            'id' => $business['id'],
            'money' => $money
        ];

        $validate = [
            [
                'money' => ['number', 'egt:0'],
            ],
            [
                'money.number'  => '余额必须是数字类型',
                'money.egt'      => '余额必须大于等于0元',
            ]
        ];

        // 用户表更新
        $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

        if ($BusinessStatus === false) {
            $this->result['msg'] = $this->BusinessModel->getError();
            $this->result['result'] = false;
            return $this->result;
        }

        $RecordData = [
            'total' => $total,
            'busid' => $business['id'],
            'content' => "{$payment}充值了￥{$total}元"
        ];

        // 消费记录表新增
        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
        if ($RecordStatus === false) {
            $this->BusinessModel->rollback();
            $this->result['msg'] = $this->RecordModel->getError();
            $this->result['result'] = false;
            return $this->result;
        }

        //将未支付的订单  修改为已支付的状态
        $PayData = [
            'id' => $ids,
            'status' => '1',
            'paytime' => time()
        ];

        $PayStatus = $this->PayModel->isUpdate(true)->save($PayData);

        if ($PayStatus === false) {
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->result['msg'] = '支付订单更新状态失败';
            $this->result['result'] = false;
            return $this->result;
        }

        if ($BusinessStatus === false || $RecordStatus === false || $PayStatus === false) {
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->PayModel->rollback();
            $this->result['msg'] = '充值失败';
            $this->result['result'] = false;
            return $this->result;
        } else {
            $this->BusinessModel->commit();
            $this->RecordModel->commit();
            $this->PayModel->commit();
            $this->result['msg'] = '充值成功';
            $this->result['result'] = true;
            return $this->result;
        }
    }

    // 课程购买
    public function subject($ids = null)
    {
        //查询充值记录
        $row = $this->PayModel->find($ids);

        if (!$row) {
            $this->result['msg'] = '支付订单不存在';
            $this->result['result'] = false;
            return $this->result;
        }

        // 充值的金额
        $total = isset($row['total']) ? $row['total'] : 0;
        $total = floatval($total);

        // 第三方参数(可多参数)
        $third = isset($row['third']) ? $row['third'] : '';

        // json字符串转换数组
        $third = json_decode($third, true);

        // 从数组获取充值的用户id
        $busid = isset($third['busid']) ? $third['busid'] : 0;
        $subid = isset($third['subid']) ? $third['subid'] : 0;
        $couid = isset($third['couid']) ? $third['couid'] : 0;

        //判断用户是否存在
        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->result['msg'] = '用户不存在';
            $this->result['result'] = false;
            return $this->result;
        }

        $subject = $this->SubjectModel->find($subid);

        if (!$subject) {
            $this->result['msg'] = '课程不存在';
            $this->result['result'] = false;
            return $this->result;
        }

        //开启事务逻辑
        $this->OrderModel->startTrans();
        $this->RecordModel->startTrans();
        $this->ReceiveModel->startTrans();
        $this->CommissionModel->startTrans();

        $OrderData = [
            'subid' => $subid,
            'busid' => $busid,
            'total' => $total,
            'code' => build_code('SUB'),
            'pay' => $row['type'],
        ];

        //订单表 校验器
        $OrderStatus = $this->OrderModel->save($OrderData);

        if ($OrderStatus === false) {
            $this->result['msg'] = $this->OrderModel->getError();
            $this->result['result'] = false;
            return $this->result;
        }

        //消费记录
        $paytext = $row['type_text'];
        $RecordData = [
            'total' => "-{$total}",
            'busid' => $busid,
            'content' => "购买了[{$subject['title']}]课程,花费了￥{$total}元 （{$paytext}）"
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
        if ($RecordStatus === false) {
            $this->OrderModel->rollback();
            $this->result['msg'] = $this->RecordModel->getError();
            $this->result['result'] = false;
            return $this->result;
        }

        //查询是否有选择优惠券
        $where = ['receive.id' => $couid, 'receive.status' => '1'];
        $coupon = $this->ReceiveModel->with(['coupon'])->where($where)->find();

        //如果有选择优惠券那么就要更新优惠券使用状态
        if ($coupon) {
            $CouponReceiveData = [
                'id' => $couid,
                'status' => '0'
            ];

            $CouponReceiveStatus =  $this->ReceiveModel->isUpdate(true)->save($CouponReceiveData);
            if ($CouponReceiveStatus === false) {
                $this->OrderModel->rollback();
                $this->RecordModel->rollback();
                $this->result['msg'] = '优惠券状态更新失败';
                $this->result['result'] = false;
                return $this->result;
            }
        }

        //判断是否有推荐人可以得到佣金
        $parentid = $business['parentid'] ? trim($business['parentid']) : 0;
        $parent = $this->BusinessModel->find($parentid);

        if ($parent) {
            //佣金比率
            $AmountRate = config('site.AmountRate') ? config('site.AmountRate') : 0.05;

            //消费金额*佣金比率 = 转给推荐人
            $amount = bcmul($total, $AmountRate, 2);

            $CommissionData = [
                'orderid' => $this->OrderModel->id,   //获取插入最后一条的自增ID
                'busid' => $busid,
                'parentid' => $parentid,
                'amount' => $amount,
                'type' => 'subject', //买课程
                'status' => '0' //未提现
            ];

            // 验证器
            $CommissionStatus = $this->CommissionModel->save($CommissionData);
            if ($CommissionStatus === false) {
                $this->OrderModel->rollback();
                $this->RecordModel->rollback();
                $this->ReceiveModel->rollback();
                $this->result['msg'] = '推荐信息存储失败';
                $this->result['result'] = false;
                return $this->result;
            }
        }

        //将未支付的订单  修改为已支付的状态
        $PayData = [
            'status' => 1,
            'paytime' => time()
        ];

        $PayStatus = $this->PayModel->where(['id' => $row['id']])->update($PayData);

        if ($PayStatus === FALSE) {
            $this->CommissionModel->rollback();
            $this->ReceiveModel->rollback();
            $this->RecordModel->rollback();
            $this->OrderModel->rollback();
            $this->result['msg'] = '支付订单更新状态失败';
            $this->result['result'] = false;
            return $this->result;
        }

        if ($OrderStatus === FALSE || $RecordStatus === FALSE) {
            $this->PayModel->rollback();
            $this->CommissionModel->rollback();
            $this->ReceiveModel->rollback();
            $this->RecordModel->rollback();
            $this->OrderModel->rollback();
            $this->result['msg'] = '购买课程失败';
            $this->result['result'] = false;
            return $this->result;
        } else {
            $this->OrderModel->commit();
            $this->RecordModel->commit();
            $this->ReceiveModel->commit();
            $this->CommissionModel->commit();
            $this->PayModel->commit();
            $this->result['msg'] = '购买课程成功';
            $this->result['result'] = true;
            return $this->result;
        }
    }
}
